import time
import re
from common.pre_config_brower import chrome_brower, request_for_sales
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


class Joann:
    def __init__(self, url):
        self.driver = chrome_brower(disableIMG=True)
        self.home_url = url
        self.main_windows_id = None
        self.open_web()

    # open the web pages
    def open_web(self):
        try:
            self.driver.get(self.home_url)
            self.main_windows_id = self.driver.window_handles[-1]
        except Exception as e:
            print("open the first page failure", e)

    # search the elements, e.g. production name , href, picture and so on
    def get_info_from_page(self):
        self.get_all_items()
        self.roll_to_top()
        time.sleep(10)
        items_num_info_list = self.driver.find_elements_by_css_selector(
            "[class='product-grid__item']")
        print(len(items_num_info_list))
        for item in items_num_info_list:
            product_info_dic = {}
            product_info_dic["productUrl"] = item.find_element_by_css_selector(
                "[class='product-tile__anchor']").get_attribute('href')
            product_info_dic["productImageUrl"] = item.find_element_by_xpath(
                './/img').get_attribute("data-src").split("?sw=")[0]

            produce_name_price = item.find_element_by_css_selector(
                "[class='product-tile__body']").text
            info_list = produce_name_price.strip().split("\n")
            product_info_dic["productName"] = info_list[0]
            product_info_dic["productPrice"] = info_list[1]
            product_info_dic["productImageName"] = product_info_dic["productName"].replace(
                " ", "_") + ".jpg"

            # print(product_info_dic)
            yield product_info_dic

    def roll_to_top(self):
        js = "var q=document.documentElement.scrollTop=10000"
        self.driver.execute_script(js)

    def get_all_items(self):
        items_total_num_text = self.driver.find_element_by_css_selector(
            "[class='plp-breadcrumb-count']").text
        print(items_total_num_text)

        num = re.findall("(\d+)", items_total_num_text)
        if num:
            self.home_url += "&start=0&sz=%s" % num[0]
            self.open_web()
